#!/usr/local/bin/python3.7
import time
import sys
import os
import logging
import pandas
import datetime
import random
import json

logging.basicConfig(filename='myapp.log', level=logging.ERROR)
logger = logging.getLogger(__name__)

argv_path = sys.argv[0]
if ((os.path.isfile(argv_path))):
    print(argv_path + ' 已找到，开始执行...')
else:
    print('File not exist!!!')
    sys.exit()

startTime = time.time()  # 计时开始
print('计时开始，当前时间为', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(startTime)))

def loadJson(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            json_data = json.load(file)
            data = []
            for row in json_data['data'].get('product_spu_list', []):
                tmp = {
                    "id": row.get('id', ''),# 商品id
                    "name": row.get('name', ''),# 商品名称
                    "origin_price": row.get('skus', '')[0].get('origin_price'),# 划线价
                    "min_price": row.get('min_price', ''),# 现价
                    "member_price": row.get('member_price', ''),# 会员价
                    "picture": row.get('picture', ''),# 商品图片
                    "month_sales": row.get('month_sales', ''),# 月销量
                    "min_order_count": row.get('skus', '')[0].get('min_order_count'),# 最低购买数量
                    "upccode": row.get('skus', '')[0].get('upccode'),
                    "stock": row.get('skus', '')[0].get('stock'),# 库存
                }
                data.append(tmp)
            return data
    except FileNotFoundError:
        print("文件未找到，请确认文件路径")
    except json.JSONDecodeError as e:
        print(f"JSON 解析失败：{e.smg} at line: {e.lineno}, col: {e.clono}")
        exit(1)

def exportExcel(exdata, exheader, fileName):
    df = pandas.DataFrame(exdata)
    try:
        # 设置Excel文件的中文标题
        df.columns = exheader
        df.to_excel(fileName+'.xlsx', index=False)
    except Exception as e:
        print(f"excel转换出错：{e}")

def mkdir(dir_path):
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)

def generate_random_filename():
    today = formatDate()
    # 生成随机数作为文件名的一部分
    random_number = random.randint(100000, 999999)
    # 生成文件名
    filename = f"{today}_{random_number}"
    return filename

def formatDate():
     # 获取当前日期
    now = datetime.datetime.now()
    # 格式化日期为字符串
    return now.strftime("%Y%m%d")

#fileName = generate_random_filename()
#create_excel(fileName)
header = [
    '商品ID','商品名称','商品原价','商品现价','会员价','商品图片','月销量','最低购买数量','upccode','库存'
]
# 创建当天目录
current_directory = formatDate()
mkdir(current_directory)
fileName = current_directory + os.sep + generate_random_filename()
exportExcel(loadJson('responseBody.txt'), header, fileName)
# 在代码的最后添加这一行
input("Press Enter to exit...")